package com.lilong.jwt.common.config;

import java.io.IOException;
import java.util.ArrayList;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.lilong.jwt.common.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 处理JWT权限认证,及统一权限处理
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain chain) throws ServletException, IOException {

        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(tokenHead)) {
            final String authToken = authHeader.substring(tokenHead.length()); // The part after "Bearer "
            String username = jwtTokenUtil.getUsernameFromToken(authToken);
            logger.info("checking authentication " + username);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                            request));
                    logger.info("authenticated user " + username + ", setting security context");
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    checkPermission(request, authentication);
                }
            }
        }
        chain.doFilter(request, response);

    }


    private void checkPermission(HttpServletRequest request, UsernamePasswordAuthenticationToken authentication) {
        AntPathRequestMatcher matcher;
        ArrayList<GrantedAuthority> grantedAuthorities= Lists.newArrayList(authentication.getAuthorities());
        grantedAuthorities.addAll(whiteList());
        for (GrantedAuthority ga : grantedAuthorities) {
            matcher = new AntPathRequestMatcher(ga.getAuthority());
            if (matcher.matches(request)) {
                return;
            }
        }
        logger.info(request.getRequestURI() + "没有访问权限");
        throw new AccessDeniedException("没有该功能的操作权限");
    }

    /**
     * 默认可以访问的权限
     */
    private ArrayList<GrantedAuthority> whiteList() {
        ArrayList<GrantedAuthority> collection = new ArrayList<>();
        collection.add(() -> "/auth/*");
        collection.add(()->"/sys/user/info");
        return collection;
    }
}

